<?php
/**
 * 小程序用户密钥模型
 *
 *
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */
defined('InShopNC') or exit('Access Invalid!');

class applet_user_secretModel extends Model {

    private $applet_arr = [ //小程序类型
        'applet_wx'    => 1,
        'applet_zfb'   => 2,
        'applet_baidu' => 3
    ];

    public function __construct(){
        parent::__construct('applet_user_secret');
    }

    /**
     *  增加小程序用户密钥
     */
    public function addAppletUserSecret($openid, $session_key, $applet_type = 'applet_wx')
    {
        if(empty($openid) || empty($session_key)) return false;
        $applet_arr = $this->applet_arr;
        $add_data['applet_type'] = isset($applet_arr[$applet_type]) ? $applet_arr[$applet_type] : 1;
        $add_data['applet_openid'] = $openid;
        $add_data['secret_salt'] = mt_rand(100000, 999999);
        $add_data['secret_key'] = md5(md5($openid . $session_key) . $add_data['secret_salt']);
        //密钥生存周期（minute）默认 : 5分钟
        $applet_secret_failure_minute = defined('APPLET_SECRET_FAILURE_MINUTE') ? APPLET_SECRET_FAILURE_MINUTE : 5;
        $add_data['last_time'] = TIMESTAMP + 60 * $applet_secret_failure_minute;

        //该用户是否存在密钥
        $map = [
            'applet_openid' => $add_data['applet_openid'],
            'applet_type'   => $add_data['applet_type']
        ];
        $secret_info = $this->table('applet_user_secret')->field('secret_id,secret_key,last_time')->where($map)->find();
        //不存在密钥
        if (empty($secret_info)) {
            $insert_id  = $this->table('applet_user_secret')->insert($add_data);
            if (!$insert_id) return false;
            $secret_key = $add_data['secret_key'];
        } elseif ($secret_info['last_time'] < TIMESTAMP) {  //存在，检查密钥生存周期是否到限，到期即更新密钥
            $update_data = [
                'secret_salt' => $add_data['secret_salt'],
                'secret_key'  => $add_data['secret_key'],
                'last_time'   => $add_data['last_time']
            ];
            $update_status = $this->table('applet_user_secret')->where(['secret_id' => (int)$secret_info['secret_id']])->update($update_data);
            if ($update_status === false) return false;
            $secret_key = $add_data['secret_key'];
        } else { //存在，且生存周期未到期
            $secret_key = $secret_info['secret_key'];
        }
        return $secret_key;
    }


    /**
     * 校验登陆密钥是否有效
     * @param  string $openid      openid
     * @param  string $secret_key  登陆密钥
     * @param  string $applet_type 小程序类型
     * @return true - 有效 / false - 无效
     */
    public function verifyAppletSecretStatus($openid, $secret_key, $applet_type = 'applet_wx')
    {
        $applet_arr = $this->applet_arr;
        $applet_type = isset($applet_arr[$applet_type]) ? $applet_arr[$applet_type] : 1;
        //校验有效期
        $map = [
            'applet_openid' => $openid,
            'applet_type' => $applet_type,
            'secret_key' => $secret_key,
            'last_time' => ['egt', TIMESTAMP]
        ];
        $if_exist = $this->table('applet_user_secret')->field('secret_id')->where($map)->find();
        return empty($if_exist) ? false : true;
    }

}
